import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res, ParseUUIDPipe, ParseIntPipe } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
import { zip } from 'compressing';
import type { Response } from 'express';
import { PPipe } from 'src/p/p.pipe';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) { }

  /* 
    使用 UseInterceptors 装饰器  FileInterceptor是单个 读取字段名称  FilesInterceptor是多个
    参数 使用 UploadedFile 装饰器接受file 文件
  */
  @Post('album')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file) {
    console.log(file);
    return '上传成功:' + file.path
  }

  @Get('export')
  downLoad(@Res() res: Response) {
    const url = join(__dirname,'../images/1756179771182.png')
    res.download(url)
  }

  @Get('stream')
  async down(@Res() res: Response) {
    const url = join(__dirname, '../images/1756179771182.png')
    const tarStream = new zip.Stream()
    await tarStream.addEntry(url)
    res.setHeader('Content-Type', 'application/octet-stream')
    res.setHeader('Content-Disposition', 'attachment; filename=xiaoman')
    tarStream.pipe(res)
  }


  @Post('login')
  create(@Body(PPipe) createUploadDto: CreateUploadDto) {
    return this.uploadService.create(createUploadDto);
  }

  @Get()
  findAll() {
    return this.uploadService.findAll();
  }

  // 可以使用内置api转换类型比如ParseUUIDPipe
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.uploadService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUploadDto: UpdateUploadDto) {
    return this.uploadService.update(+id, updateUploadDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.uploadService.remove(+id);
  }
}
